package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        Query query =Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        boolean exists = mongoTemplate.exists(query, Visitors.class);
        if(!exists){
            mongoTemplate.save(visitors);
        }
    }

    @Override
    public List<Visitors> findVisitors(Long userId, Long date) {
        Criteria criteria=Criteria.where("userId").is(userId);
        if(date!=null){
            criteria.and("date").gt(date);
        }
        Query query =Query.query(criteria).limit(5);
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }
}
